package com.xcdh.trading.util;

import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xcdh.trading.entity.Tweet;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class TweetParser {
    private static final DateTimeFormatter TWITTER_DATE_FORMAT =
        DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    private static final DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    public static List<Tweet> parseTweets(String json) {
        List<Tweet> result = new ArrayList<>() ;
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode root = mapper.readTree(json);
            JsonNode tweets = root.get("data");
            for (JsonNode tweet : tweets) {
                String text = tweet.get("text").asText();
                String createdAt = tweet.get("created_at").asText();
                String id = tweet.get("id").asText();
                LocalDateTime time = LocalDateTime.parse(createdAt, TWITTER_DATE_FORMAT);
                String format = time.format(outputFormat);
                Tweet tweet1 = new Tweet() ;
                tweet1.setText(text);
                tweet1.setUserId("44196397");
                tweet1.setPostDate(format);
                tweet1.setCreateTime(DateUtil.formatDateTime(new Date()));
                tweet1.setId(id);
                result.add(tweet1) ;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
